package ngram_reader.viewer;

import ngram_reader.viewer.query.Accumulator;
import function.unary.UnaryFunction;
import java.io.DataInputStream;
import java.io.File;
import java.util.List;
import ngram.reader.V1FileReader;
import ngram.util.IOUtil;
import ngram_reader.viewer.query.NGramSearchQuery;
import swingExtended.EstimatingProgressBar;
import swingExtended.progressPanel.ProgressPanel;

/**
 *
 * @author Shimu
 * @date 10-Nov-2013
 */
public class NGramSearch_V1 extends NGramSearch {

    public NGramSearch_V1(ProgressPanel panel, List<File> inputDirs,
            NGramSearchQuery query, EstimatingProgressBar progressBar) {
        super(panel, inputDirs, query, progressBar);
    }

    @Override
    protected void process(String fileUrl) throws Exception {
        try (DataInputStream stream = IOUtil.getDataInputStream(fileUrl)) {
            String n_gram;

            UnaryFunction<String, Boolean> isTarget = this.searchQuery.getIsTarget();

            Accumulator yearMatchVolumeAc = this.searchQuery.getAccumulator();

            V1FileReader reader = new V1FileReader(stream);

            while (!isCancelled() && (n_gram = reader.readNGram()) != null) {
                // The number of year, count information that follows
                int count = reader.readHeader();

                if (isTarget.evaluate(n_gram)) {
                    if (searchQuery.ignoreStatistics()) {
                        reader.skip(count);

                        publishText(n_gram, true);
                    } else {
                        for (int i = 0; i < count; i++) {
                            int year = reader.readYear();
                            long match_count = reader.readMatchCount();
                            long volume_count = reader.readVolumeCount();
                            yearMatchVolumeAc.accumulate(year, match_count, volume_count);
                        }
                        final String value = yearMatchVolumeAc.getAccumulatedValue();
                        yearMatchVolumeAc.reset();
                        if (!value.isEmpty()) {
                            publishText(n_gram, true);
                            publishText("year\tmatch count\tvolume count\n", false);
                            publishText(value, false);
                        }
                    }

                } else {
                    // Skip the year, count information since the n-gram
                    // is not our target
                    reader.skip(count);
                }
            }
        }
    }
}
